package com.tanhua.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.admin.Admin;
import com.tanhua.model.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存生成的验证码
     *
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = Constants.CAP_CODE + uuid;
        // 缓存验证码，10分钟后失效
        stringRedisTemplate.opsForValue().set(key, code, Duration.ofMinutes(10));
    }

    /**
     * 用户登录校验账号密码和验证码
     *
     * @param params
     * @return
     */
    public Map<String, String> login(Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        String verificationCode = params.get("verificationCode");
        String uuid = params.get("uuid");
        String key = Constants.CAP_CODE + uuid;
        if (StringUtils.isEmpty(verificationCode)) {
            throw new BusinessException("请输入验证码");
        }
        String redisKey = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(redisKey)) {
            throw new BusinessException("验证码已过期，请重新获取");
        }
        stringRedisTemplate.delete(key);
        if (!StringUtils.equals(redisKey, verificationCode)) {
            throw new BusinessException("验证码错误，请重新输入");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Admin admin = query().eq("username", username).eq("password", password).one();
        if (BeanUtil.isEmpty(admin)) {
            throw new BusinessException("用户名或密码错误");
        }
        String token = JwtUtils.createToken(admin.getId(), admin.getUsername());
        String adminJson = JSON.toJSONString(admin);
        String tokenKey = "TOKEN_" + token;
        stringRedisTemplate.opsForValue().set(tokenKey, adminJson);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    /**
     * 用户登录后详细信息
     *
     * @return
     */
    public AdminVo profile() {
        Admin admin = AdminHolder.getAdmin();
        AdminVo init = AdminVo.init(admin);
        return init;
    }

    /**
     * 退出登录
     *
     * @return
     */
    public void logout(String token) {
        token = token.replace("Bearer", "");
        String key = "TOKEN_" + token;
        stringRedisTemplate.delete(key);
    }
}
